#from Accounting.Entity.Client import *
from Error.ExtendError import CorrspondingSubscription_NA
from DataAccess.DBConnFactory import DBConnFactory
from string import Template

def is_pay_day(ref_date, entity, subtype):
	cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
	sql_tpl = Template('''select ref_date 
						from fee_schedule_calc_ex
						where entity='${ENTITY}'
							and subtype='${FSTP}'
							and is_pay_day='T'								
							and ref_date=TO_DATE('${DATE}','yyyy-mm-dd')''')
	sql_text = sql_tpl.substitute(ENTITY = entity.get_entity_id(),
								FSTP = subtype,
								DATE = ref_date.isoformat())
	cursor.execute(sql_text)
	r = cursor.fetchall()	
	#print 'is_pay_day', ref_date.isoformat(), entity.get_entity_id(), subtype
	#print r
	
	if len(r) > 0:
		return True
	else:
		return False

	
def watermark(ref_date, entity, subtype):
	cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
	sql_tpl = Template('''select * from
						(select av.ref_date,av.avpu,NVL(fc.watermark_min,-1), fc.inception
						from asset_value_ex av,fee_conf fc,
								((select fs.ref_date as ref_date from fee_schedule_calc_ex fs,fee_conf fc
								where fs.entity=fc.entity
									and fs.subtype=fc.subtype
									and fs.is_pay_day='T'
									and fs.ref_date>fc.inception
									and fs.ref_date<TO_DATE('${DATE}','yyyy-mm-dd')
									and fc.entity='${ENTITY}'
									and fc.subtype='${FCTP}')	
								union
								(select inception from fee_conf
								where entity='${ENTITY}'
									and subtype='${FCTP}')) fse
							where av.ref_date=fse.ref_date 
								and av.entity=fc.entity
								and av.type=fc.watermark_ref								
								and fc.entity='${ENTITY}' 
								and fc.subtype='${FCTP}'	
							order by av.avpu desc)
						where rownum<=1''')
	cursor.execute(sql_tpl.substitute(ENTITY = entity.get_entity_id(),
										FCTP = subtype,
										DATE = ref_date.isoformat()))
	r = cursor.fetchall()
	if not r:
		raise RuntimeError(), ("Watermark Error")
	
	if r[0][1] < r[0][2]:
		return (r[0][3], r[0][2])
	else:
		return (r[0][0], r[0][1])
		
	
def GAV_per_share(ref_date, entity):
	cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
	sql_tpl = Template('''select avpu from asset_value_ex 
						where type='${TP}' 
							and ref_date=TO_DATE('${DATE}','yyyy-mm-dd')
							and entity='${ENTITY}' ''')		
	cursor.execute(sql_tpl.substitute(ENTITY = entity.get_entity_id(),
										TP = 'GAV',
										DATE = ref_date.isoformat()))
	r = cursor.fetchall()
	if not r:
		raise RuntimeError(), ("Asset Value Per Unit Error")	
	
	return r[0][0]
	
def is_peak(ref_date, entity, log_file=None):
	is_pk = False
	
	#tmp = is_pay_day(ref_date, entity, 'inv_perf_fee') 
	#log_file.write(ref_date.isoformat()+str(tmp)+ '\n')
	#print 'is_peak',ref_date.isoformat()+ '\n'
	
	if is_pay_day(ref_date, entity, 'inv_perf_fee'):	
		pre_peak = watermark(ref_date, entity, 'inv_perf_fee')
		
		#if ref_date==date(2007,12,31) or ref_date==date(2007,11,30):
		#	log_file.write(entity.get_entity_id() + '\n')
		#	log_file.write('pre_peak=',pre_peak,"GAV_per_share(ref_date, entity)",GAV_per_share(ref_date, entity)+'\n')
	
		if GAV_per_share(ref_date, entity) > pre_peak[1]:
			is_pk = True
	
	return is_pk
	
def share_amt_conv_type(ref_date, entity):
	
	#debug
	#log_file = open('D:/work/pke/testcases/dump.log', 'a')		
	#log_file.write('debug, share_amt_conv_type, '+entity.get_entity_id()+'\n')
	#print 'share_amt_conv_type',ref_date.isoformat()+entity.get_entity_id()+ '\n'
	
	#if not isinstance(entity, Client):
	if not is_client_entity(entity):
		#log_file.write('debug, is_not_client_entity. \n')
		return 'NAV'
	
	if is_peak(ref_date, entity.get_parent()):
		conv_by = 'NAV'
	else:
		conv_by = 'GAV'
	
	#print 'conv_by',conv_by
	return conv_by
	

def query_first_subscription_id(parent, child):
	#if not ininstance(child, Client):
	if not is_client_entity(child):
		return None
	
	cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
	sql_tpl = Template('''select id
					from feeder_remain_share
					where parent='${P}' 
						and child='${C}' 
						and shares>0
					order by ref_date asc''')
	sql_text = sql_tpl.substitute(P=parent.get_entity_id(),
								  C=child.get_entity_id())
	cursor.execute(sql_text)
	r = cursor.fetchone()
	if r and len(r)>0:
		corr_id = r[0]
		return corr_id
	else:
		raise CorrspondingSubscription_NA(), sql_text

		
		
def util_query_avpu(ref_date, entity):
	cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
	sql_tpl = Template('''select avpu from asset_value_ex 
					where ref_date=TO_DATE('${DATE}','yyyy-mm-dd')
					and entity='${ENTITY}' ''')
	sql_text = sql_tpl.substitute(DATE=ref_date.isoformat(), 
								ENTITY=entity)
	cursor.execute(sql_text)
	r = cursor.fetchone()
	if r and len(r)>0:
		return r[0]
	else:
		return None	
		
		
def is_client_entity(entity, log_file=None):
	class_name = str(entity.__class__)[len(entity.__module__)+1:]
	#debug
	#if log_file:
	#	log_file.write(entity.get_entity_id()+':'+str(entity.__class__)+'\n')
	#	log_file.write(entity.get_entity_id()+':'+entity.__module__+'\n')
	#	log_file.write(entity.get_entity_id()+':'+class_name+'\n')		
	
	if class_name == 'Client':
		return True
	else:
		return False	